package com.hzmg.handler;

import akka.actor.typed.ActorSystem;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import com.hzmg.filter.GatewayFilter;
import com.hzmg.filter.LoadBalancerClientFilter;
import com.hzmg.filter.RequestAndResponseFilter;
import com.hzmg.route.Shift;
import com.hzmg.route.RouteDefinition;
import com.hzmg.support.util.NameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class RouteDefinitionHandler {

    private static final Logger logger = LoggerFactory.getLogger(RouteDefinitionHandler.class);

    public static final Behavior<Shift> create() {
        return Behaviors.setup(
                context -> {
                    logger.info("[akkacloud-gateway-core] RouteDefinitionHandler: String worker {}");

                    return Behaviors.receive(Shift.class)
                            .onMessage(RouteDefinition.class, routeDefinition ->
                                    onRouteDefinition(context, routeDefinition))
                            .build();
                }
        );
    }

    private static Behavior<Shift> onRouteDefinition(ActorContext<Shift> context, RouteDefinition routeDefinition) {
        logger.info("[akkacloud-gateway-core] RouteDefinitionHandler: {}", context);
        //TODO: Improve how filters are implemented
        List<GatewayFilter> filters = new ArrayList<>();
        filters.add(new LoadBalancerClientFilter());
        AkkaFilterHandler filterHandler = new AkkaFilterHandler(filters);
        ActorSystem<Void> filterRef = ActorSystem.create(
                filterHandler.handle(routeDefinition),
                NameUtils.normalizeActorRefSimpleName(RouteDefinitionHandler.class)
        );

        RequestAndResponseFilter.messageHandle(context, routeDefinition);

        return Behaviors.same();
    }


}
